import { removeLoginInfoStorageSync, getLoginInfoStorageSync } from '@/utils/storageSync'

// 基础配置
export const baseConfig = {
  uploadURL: 'http://192.168.1.106:7801/',
  // baseURL: 'http://192.168.1.105:48080/admin-api',
  baseURL: 'http://1.13.0.199:8214',
  timeout: 10000,
  header: {
    'Content-Type': 'application/json'
  }
}

// 请求拦截器
const requestInterceptor = (config) => {
  const tokenExpireTime = uni.getStorageSync('expireTime')
  if (tokenExpireTime) {
    const currentTime = new Date().getTime()
    if (currentTime > tokenExpireTime) {
      removeLoginInfoStorageSync()
      uni.redirectTo({
        url: '/pages/login/index'
      })
      return
    }
  }

  // 获取token
  const accessToken = getLoginInfoStorageSync().token
  if (accessToken) {
    // 根据web端格式，直接使用Token字段，不加Bearer前缀
    config.header.Token = accessToken
  }

  // 拼接完整的URL
  if (!config.url.startsWith('http')) {
    // 移除baseURL末尾的斜杠(如果有)
    const base = baseConfig.baseURL.replace(/\/+$/, '')
    // 移除url开头的斜杠(如果有)
    const path = config.url.replace(/^\/+/, '')
    config.url = `${base}/${path}`
  }

  return config
}

// 响应拦截器
const responseInterceptor = (response) => {
  const { data } = response

  const { code } = data

  // 请求成功
  if (code == 0) {
    return data
  }

  // 401: 未登录或token过期
  if (code === 401) {
    uni.removeStorageSync('token')
    uni.redirectTo({
      url: '/pages/login/index'
    })
    return
  } else {
    // 其他错误
    const msg = data?.msg || data?.message || '请求失败'
    uni.showToast({
      title: msg,
      icon: 'none',
      duration: 2000
    })
    return data
  }
}

// 请求函数
const request = (options = {}) => {
  // 合并配置
  const config = {
    ...baseConfig,
    ...options,
    header: {
      ...baseConfig.header,
      ...options.header
    }
  }

  // 请求拦截
  const finalConfig = requestInterceptor(config)

  // 发起请求
  return new Promise((resolve, reject) => {
    uni.request({
      ...finalConfig,
      success: (res) => {
        try {
          const result = responseInterceptor(res)
          resolve(result)
        } catch (error) {
          reject(error)
        }
      },
      fail: (err) => {
        console.error('请求失败:', err) // 调试用
        uni.showToast({
          title: '网络异常',
          icon: 'none',
          duration: 2000
        })
        reject(err)
      }
    })
  })
}

export default request
